﻿using System.IO;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using Mvc3Blog.Models;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace Mvc3Blog.Infrastructure
{
    public static class SQLiteUtil
    {
        private const string DbName = "Blog.db";
        private static ISessionFactory _fnhSessionFactory;

        public static ISessionFactory SessionFactory
        {
            get
            {
                if (null != _fnhSessionFactory) return _fnhSessionFactory;
                _fnhSessionFactory = Fluently.Configure()
                    .Database(SQLiteConfiguration.Standard.UsingFile(DbName))
                    .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Post>(new BlogDbMappingConfiguration())))
                    .ExposeConfiguration(c =>
                                             {
                                                 if (!File.Exists(DbName))
                                                     new SchemaExport(c).Create(true, true);
                                             })
                    .BuildSessionFactory();

                return _fnhSessionFactory;
            }
        }
    }
}